package com.linln.admin.pcs.controller;


import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.linln.admin.config.IDCardEncryptor;
import com.linln.admin.config.SmsUtils;
import com.linln.admin.pcs.api.SlabApiController;
import com.linln.admin.pcs.service.OrderTempService;
import com.linln.admin.pcs.service.TemplateMessageService;
import com.linln.admin.pcs.service.WechatPayRefundService;
import com.linln.admin.system.service.AppService;
import com.linln.common.data.QuerySpec;
import com.linln.common.utils.*;
import com.linln.component.actionLog.annotation.EntityParam;
import com.linln.component.shiro.ShiroUtil;
import com.linln.modules.system.domain.*;
import com.linln.modules.system.repository.*;
import com.linln.modules.system.service.OrderPortersService;
import com.linln.modules.system.service.PorterService;
import com.linln.modules.system.service.SmsLogService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.persistence.criteria.Predicate;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;


/**
 * 订单信息管理
 */
@Controller
@RequestMapping("/pcs/order_commission")
public class OrderCommissionController {

    @Autowired
    private AppService appService;
    @Autowired
    private PorterRepository porterRepository;
    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;
    @Autowired
    private PorterPermissionRepository porterPermissionRepository;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private PatientRepository patientRepository;
    @Autowired
    private PatientAdmissionRepository patientAdmissionRepository;
    @Autowired
    private OrderPortersRepository orderPortersRepository;
    @Autowired
    private OrderLogsRepository orderLogsRepository;
    @Autowired
    private  CompanyRepository companyRepository;
    @Autowired
    private  ComplainRepository complainRepository;
    @Autowired
    private PorterService porterService;
    @Autowired
    private WechatPayRefundService wechatPayRefundService;
    @Autowired
    private OrderPortersService orderPortersService;
    @Autowired
    private ProjectRepository projectRepository;
    @Autowired
    private EvaluateRepository evaluateRepository;
    @Autowired
    private MsgRepository msgRepository;
    @Autowired
    private TemplateMessageService templateMessageService;
    @Autowired
    private SmsLogService smsLogService;
    @Autowired
    private OrderTempService orderTempService;
    @Autowired
    private PayRecordRepository payRecordRepository;
    @Autowired
    private OrderCommissionRepository orderCommissionRepository;
    @Autowired
    private OrderCommissionLogRepository orderCommissionLogRepository;


    private final static Logger logger = LoggerFactory.getLogger(OrderCommissionController.class);

    /**
     * 佣金列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("pcs:OrderCommission:index")
    public ResponseEntity<?> index(Model model, @EntityParam OrderCommission orderCommission) {
        return appService.layTable(orderCommissionRepository, before -> {
                    model.addAttribute("porterName", HttpServletUtil.getParameter("porterName",""));
                    model.addAttribute("orderStatus", HttpServletUtil.getParameter("orderStatus",""));
                    // 添加模板变量
                    return model;

                },

                after -> {
                    QuerySpec querySpec = QuerySpec.matching();
                    querySpec.withMatcher("patientName", QuerySpec.LIKE)
                            .withMatcher("sn", QuerySpec.LIKE)
                            .withMatcher("type", QuerySpec.EQUAL)
                            .withMatcher("porterName", QuerySpec.LIKE);
                    User user = ShiroUtil.getSubject();
                    if (user.getType()!=null&&user.getType().equals("2")) {
                        Long companyId = user.getCompanyId();
                        querySpec.withMatcherValue("companyId", QuerySpec.EQUAL,companyId.toString());
                    }
                    return QuerySpec.of(querySpec);
                },

                "/pcs/order_commission/index",

                (pageResult) -> {
                    // 在这里处理 pageResult
                    // 例如：修改每一条数据
                    pageResult.getContent().forEach(item -> {

                    });
                }

        );

    }





    /**
     * 专业陪护订单详情
     */
    @GetMapping("/detail")
    @RequiresPermissions("pcs:OrderCommission:index")
    public String detail(@RequestParam Long id, Model model) throws Exception{
        OrderCommission data = orderCommissionRepository.getById(id);
        model.addAttribute("data", data);

        //查询患者信息
        Patient patient = patientRepository.getById(data.getPatientId());
        if(patient!=null){
            patient.setCardNo(IDCardEncryptor.aesTuoMinDecrypt(patient.getCardNo()));
            patient.setPhone(IDCardEncryptor.aesTuoMinPhoneDecrypt(patient.getPhone()));
        }

        model.addAttribute("patient", patient);


        //查询佣金明细信息
        QuerySpec querySpec1 = QuerySpec.matching();
        querySpec1.withMatcherValue("orderId", QuerySpec.EQUAL,data.getOrderId().toString());
        List<OrderCommissionLog> orderCommissionLogs = orderCommissionLogRepository.findAll(QuerySpec.of(querySpec1));
        model.addAttribute("orderCommissionLogs", orderCommissionLogs);

        return "/pcs/order_commission/detail";
    }



//    @PostMapping("/count_commission")
//    public ResponseEntity<?> countCommission() {
//        // 假设当前操作的系统用户ID
//       // Long systemUserId = 1L; // 根据实际情况获取
//
//        // 查询需要计算佣金的订单：未计算过佣金且订单状态>5（已完成）
//        QuerySpec querySpec = QuerySpec.matching();
//        querySpec.withMatcherValue("isCountCommission", QuerySpec.NOT_EQUAL, "1")
//                .withMatcherValue("orderStatus", QuerySpec.GE, "5");
//        List<Order> orderList = orderRepository.findAll(QuerySpec.of(querySpec));
//
//        for (Order order : orderList) {
//            // 获取项目佣金比例
//            Project project = projectRepository.findById(order.getProjectId()).orElse(null);
//            if (project == null || project.getCommissionRate() == null) {
//                continue; // 跳过无佣金比例的项目
//            }
//            BigDecimal commissionRate = BigDecimal.valueOf(project.getCommissionRate())
//                    .divide(BigDecimal.valueOf(100), 4, RoundingMode.HALF_UP);
//            BigDecimal totalCommission = BigDecimal.valueOf(order.getTotal())
//                    .multiply(commissionRate)
//                    .setScale(2, RoundingMode.HALF_UP); // 订单总佣金
//            if( order.getType()==1){
//                //陪护订单
//                // 获取该订单的所有有效护工记录（排除已取消的服务）
//                QuerySpec portersQuery = QuerySpec.matching();
//                portersQuery.withMatcherValue("orderId", QuerySpec.EQUAL, String.valueOf(order.getId()));
//                List<OrderPorters> orderPortersList = orderPortersRepository.findAll(QuerySpec.of(portersQuery));
//
//                if (orderPortersList.isEmpty()) {
//                    continue; // 无有效护工记录
//                }
//
//                // 解析订单每日工作时间段
//                LocalTime dailyStartTime = LocalTime.parse(order.getTimeStart());
//                LocalTime dailyEndTime = LocalTime.parse(order.getTimeEnd());
//                boolean isCrossDay = order.getTransDay() == 1; // 是否跨日服务
//
//                // 计算每个护工的服务时长（小时）和佣金
//                List<BigDecimal> porterCommissions = new ArrayList<>();
//                List<Long> porterIds = new ArrayList<>();
//                List<String> porterNames = new ArrayList<>();
//                BigDecimal totalServiceHours = BigDecimal.ZERO;
//
//                // 1. 先计算总服务时长
//                for (OrderPorters porter : orderPortersList) {
//                    BigDecimal hours = calculatePorterServiceHours(
//                            porter.getTimeStar(),
//                            porter.getTimeEnd(),
//                            dailyStartTime,
//                            dailyEndTime,
//                            isCrossDay
//                    );
//                    totalServiceHours = totalServiceHours.add(hours);
//                }
//
//                // 2. 计算每个护工的佣金
//                for (OrderPorters porter : orderPortersList) {
//                    BigDecimal hours = calculatePorterServiceHours(
//                            porter.getTimeStar(),
//                            porter.getTimeEnd(),
//                            dailyStartTime,
//                            dailyEndTime,
//                            isCrossDay
//                    );
//
//                    // 计算护工应得佣金（按服务时长比例分配总佣金）
//                    BigDecimal porterCommission = BigDecimal.ZERO;
//                    if (totalServiceHours.compareTo(BigDecimal.ZERO) > 0) {
//                        porterCommission = totalCommission.multiply(hours)
//                                .divide(totalServiceHours, 2, RoundingMode.HALF_UP);
//                    }
//                    porter.setPorter(porterRepository.getById( porter.getPorterId()));
//
//                    porterCommissions.add(porterCommission);
//                    porterIds.add(porter.getPorterId());
//                    porterNames.add(porter.getPorter().getName());
//
//                    // 保存到佣金明细表
//                    OrderCommissionLog log = new OrderCommissionLog();
//                    log.setSn(order.getSn());
//                    log.setOrderId(order.getId());
//                    log.setProjectTitle(order.getProjectTitle());
//                    log.setPorterId(porter.getPorterId());
//                    log.setPorterName(porter.getPorter().getName());
//                    log.setCommission(porterCommission.doubleValue());
//                    log.setOrderStatus(order.getOrderStatus());
//                    log.setTimeStar(porter.getTimeStar());
//                    log.setTimeEnd(porter.getTimeEnd());
//
//                    orderCommissionLogRepository.save(log);
//                }
//
//                // 3. 准备护工ID和姓名字符串（逗号分隔）
//                String porterIdsStr = porterIds.stream()
//                        .map(String::valueOf)
//                        .collect(Collectors.joining(","));
//                String porterNamesStr = String.join(",", porterNames);
//
//                // 4. 保存到佣金主表（每个订单一条记录）
//                OrderCommission orderCommission = new OrderCommission();
//                orderCommission.setSn(order.getSn());
//                orderCommission.setOrderId(order.getId());
//                orderCommission.setPatientId(order.getPatientId());
//                orderCommission.setProjectTitle(order.getProjectTitle());
//                orderCommission.setTotal(order.getTotal());
//                orderCommission.setPorterId(porterIdsStr); // 所有护工ID（逗号分隔）
//                orderCommission.setPorterName(porterNamesStr); // 所有护工姓名（逗号分隔）
//                orderCommission.setBedNo(order.getBedNo());
//                orderCommission.setDepName(order.getDepName());
//                orderCommission.setType(order.getType());
//                orderCommission.setCompanyId(order.getCompanyId());
//                orderCommission.setOrderStatus(order.getOrderStatus());
//                orderCommission.setCommission(totalCommission.doubleValue()); // 订单总佣金
//                orderCommission.setTimeStart(order.getTimeStart());
//                orderCommission.setTimeEnd(order.getTimeEnd());
//                orderCommission.setStartDay(order.getStartDay());
//                orderCommission.setEndTime(order.getEndTime());
//                orderCommission.setPatientName(order.getPatientName());
//
//                orderCommissionRepository.save(orderCommission);
//
//            }else{
//                //陪诊陪检订单
//                // 保存到佣金明细表
//                OrderCommissionLog log = new OrderCommissionLog();
//                log.setSn(order.getSn());
//                log.setOrderId(order.getId());
//                log.setProjectTitle(order.getProjectTitle());
//                log.setPorterId(order.getPorterId());
//                log.setPorterName(order.getPorterName());
//                log.setCommission(totalCommission.doubleValue());
//                log.setOrderStatus(order.getOrderStatus());
//                orderCommissionLogRepository.save(log);
//                // 4. 保存到佣金主表（每个订单一条记录）
//                OrderCommission orderCommission = new OrderCommission();
//                orderCommission.setSn(order.getSn());
//                orderCommission.setOrderId(order.getId());
//                orderCommission.setPatientId(order.getPatientId());
//                orderCommission.setProjectTitle(order.getProjectTitle());
//                orderCommission.setTotal(order.getTotal());
//                orderCommission.setPorterId(String.valueOf(order.getPorterId())); // 所有护工ID（逗号分隔）
//                orderCommission.setPorterName(order.getPorterName()); // 所有护工姓名（逗号分隔）
//                orderCommission.setBedNo(order.getBedNo());
//                orderCommission.setDepName(order.getDepName());
//                orderCommission.setType(order.getType());
//                orderCommission.setCompanyId(order.getCompanyId());
//                orderCommission.setOrderStatus(order.getOrderStatus());
//                orderCommission.setCommission(totalCommission.doubleValue()); // 订单总佣金
//                orderCommission.setTimeStart(order.getTimeStart());
//                orderCommission.setTimeEnd(order.getTimeEnd());
//                orderCommission.setStartDay(order.getStartDay());
//                orderCommission.setEndTime(order.getEndTime());
//                orderCommission.setPatientName(order.getPatientName());
//
//                orderCommissionRepository.save(orderCommission);
//            }
//
//
//
//
//
//            // 5. 标记订单佣金已计算
//            order.setIsCountCommission(1);
//            orderRepository.save(order);
//        }
//        return ResponseEntity.ok(ResultVoUtil.success("成功"));
//    }
//
//    // 计算护工实际服务时长（小时） - 使用BigDecimal保证精度
//    private BigDecimal calculatePorterServiceHours(
//            String startTimeStr,
//            String endTimeStr,
//            LocalTime dailyStart,
//            LocalTime dailyEnd,
//            boolean isCrossDay
//    ) {
//        // 添加空值检查
//        if (StringUtils.isBlank(startTimeStr) || StringUtils.isBlank(endTimeStr)) {
//            throw new IllegalArgumentException("时间参数不能为空，startTime: " + startTimeStr + ", endTime: " + endTimeStr);
//        }
//
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        try {
//            LocalDateTime start = LocalDateTime.parse(startTimeStr, formatter);
//            LocalDateTime end = LocalDateTime.parse(endTimeStr, formatter);
//
//            BigDecimal totalHours = BigDecimal.ZERO;
//            LocalDate currentDate = start.toLocalDate();
//
//            while (!currentDate.isAfter(end.toLocalDate())) {
//                // 构建当天的工作时间段
//                LocalDateTime workStart = currentDate.atTime(dailyStart);
//                LocalDateTime workEnd;
//                if (isCrossDay) {
//                    workEnd = currentDate.plusDays(1).atTime(dailyEnd); // 跨日：结束在次日
//                } else {
//                    workEnd = currentDate.atTime(dailyEnd);
//                }
//
//                // 计算当天实际服务时间段
//                LocalDateTime effectiveStart = start.isAfter(workStart) ? start : workStart;
//                LocalDateTime effectiveEnd = end.isBefore(workEnd) ? end : workEnd;
//
//                if (effectiveStart.isBefore(effectiveEnd)) {
//                    long minutes = Duration.between(effectiveStart, effectiveEnd).toMinutes();
//                    totalHours = totalHours.add(BigDecimal.valueOf(minutes).divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP));
//                }
//
//                currentDate = currentDate.plusDays(1);
//            }
//
//            return totalHours;
//        } catch (DateTimeParseException e) {
//            throw new IllegalArgumentException("时间格式错误，要求格式: yyyy-MM-dd HH:mm:ss，实际值 start: "
//                    + startTimeStr + ", end: " + endTimeStr, e);
//        }
//    }



    @PostMapping("/count_commission")
    public ResponseEntity<?> countCommission() {
        // 查询需要计算佣金的订单：未计算过佣金且订单状态>=5（已完成）
        QuerySpec querySpec = QuerySpec.matching();
        querySpec.withMatcherValue("isCountCommission", QuerySpec.NOT_EQUAL, "1")
                .withMatcherValue("orderStatus", QuerySpec.GE, "5");
        User user = ShiroUtil.getSubject();
        if (user.getType()!=null&&user.getType().equals("2")) {
            Long companyId = user.getCompanyId();
            querySpec.withMatcherValue("companyId", QuerySpec.EQUAL,companyId.toString());
        }
        List<Order> orderList = orderRepository.findAll(QuerySpec.of(querySpec));

        for (Order order : orderList) {
            try {
                // 获取项目佣金比例
                Project project = projectRepository.findById(order.getProjectId()).orElse(null);
                if (project == null || project.getCommissionRate() == null) {
                    logger.warn("订单 {} 无有效佣金比例，跳过处理", order.getSn());
                    continue;
                }

                BigDecimal commissionRate = BigDecimal.valueOf(project.getCommissionRate())
                        .divide(BigDecimal.valueOf(100), 4, RoundingMode.HALF_UP);
                BigDecimal totalCommission = BigDecimal.valueOf(order.getTotal())
                        .multiply(commissionRate)
                        .setScale(2, RoundingMode.HALF_UP);

                if (order.getType() == 1) {
                    // 陪护订单处理逻辑
                    handleAccompanyOrder(order, totalCommission);
                } else {
                    // 陪诊陪检订单处理逻辑
                    handleInspectionOrder(order, totalCommission);
                }

                // 标记订单佣金已计算
                order.setIsCountCommission(1);
                orderRepository.save(order);

            } catch (Exception e) {
                logger.error("处理订单 {} 时发生异常，已跳过。异常信息：{}", order.getSn(), e.getMessage(), e);
                continue; // 跳过当前订单继续执行
            }
        }
        return ResponseEntity.ok(ResultVoUtil.success("佣金计算完成"));
    }
    private void handleInspectionOrder(Order order, BigDecimal totalCommission){
        //陪诊陪检订单
        // 保存到佣金明细表
        OrderCommissionLog log = new OrderCommissionLog();
        log.setSn(order.getSn());
        log.setOrderId(order.getId());
        log.setProjectTitle(order.getProjectTitle());
        log.setPorterId(order.getPorterId());
        log.setPorterName(order.getPorterName());
        log.setCommission(totalCommission.doubleValue());
        log.setOrderStatus(order.getOrderStatus());
        orderCommissionLogRepository.save(log);
        // 4. 保存到佣金主表（每个订单一条记录）
        OrderCommission orderCommission = new OrderCommission();
        orderCommission.setSn(order.getSn());
        orderCommission.setOrderId(order.getId());
        orderCommission.setPatientId(order.getPatientId());
        orderCommission.setProjectTitle(order.getProjectTitle());
        orderCommission.setTotal(order.getTotal());
        orderCommission.setPorterId(String.valueOf(order.getPorterId())); // 所有护工ID（逗号分隔）
        orderCommission.setPorterName(order.getPorterName()); // 所有护工姓名（逗号分隔）
        orderCommission.setBedNo(order.getBedNo());
        orderCommission.setDepName(order.getDepName());
        orderCommission.setType(order.getType());
        orderCommission.setCompanyId(order.getCompanyId());
        orderCommission.setOrderStatus(order.getOrderStatus());
        orderCommission.setCommission(totalCommission.doubleValue()); // 订单总佣金
        orderCommission.setTimeStart(order.getTimeStart());
        orderCommission.setTimeEnd(order.getTimeEnd());
        orderCommission.setStartDay(order.getStartDay());
        orderCommission.setEndTime(order.getEndTime());
        orderCommission.setPatientName(order.getPatientName());

        orderCommissionRepository.save(orderCommission);
    }
    private void handleAccompanyOrder(Order order, BigDecimal totalCommission) {
        try {
            // 获取有效护工记录
            QuerySpec portersQuery = QuerySpec.matching();
            portersQuery.withMatcherValue("orderId", QuerySpec.EQUAL, String.valueOf(order.getId()));
            List<OrderPorters> orderPortersList = orderPortersRepository.findAll(QuerySpec.of(portersQuery));

            if (orderPortersList.isEmpty()) {
                logger.warn("订单 {} 无有效护工记录，跳过处理", order.getSn());
                return;
            }

            // 解析每日工作时间段（增加格式校验）
            LocalTime dailyStartTime = parseTime(order.getTimeStart(), "订单每日开始时间");
            LocalTime dailyEndTime = parseTime(order.getTimeEnd(), "订单每日结束时间");
            boolean isCrossDay = order.getTransDay() == 1;

            // 计算服务时长和佣金
            List<BigDecimal> porterCommissions = new ArrayList<>();
            List<Long> porterIds = new ArrayList<>();
            List<String> porterNames = new ArrayList<>();
            BigDecimal totalServiceHours = BigDecimal.ZERO;

            // 计算总服务时长
            for (OrderPorters porter : orderPortersList) {
                try {
                    BigDecimal hours = calculatePorterServiceHours(
                            porter.getTimeStar(),
                            porter.getTimeEnd(),
                            dailyStartTime,
                            dailyEndTime,
                            isCrossDay
                    );
                    totalServiceHours = totalServiceHours.add(hours);
                } catch (Exception e) {
                    logger.error("护工 {} 服务时间数据异常，已跳过。异常信息：{}",
                            porter.getPorterId(), e.getMessage());
                    continue; // 跳过当前护工
                }
            }

            // 分配佣金
            for (OrderPorters porter : orderPortersList) {
                try {
                    // 计算服务时长
                    BigDecimal hours = calculatePorterServiceHours(
                            porter.getTimeStar(),
                            porter.getTimeEnd(),
                            dailyStartTime,
                            dailyEndTime,
                            isCrossDay
                    );

                    // 计算护工应得佣金（按服务时长比例分配总佣金）
                    BigDecimal porterCommission = BigDecimal.ZERO;
                    if (totalServiceHours.compareTo(BigDecimal.ZERO) > 0) {
                        porterCommission = totalCommission.multiply(hours)
                                .divide(totalServiceHours, 2, RoundingMode.HALF_UP);
                    }
                    porter.setPorter(porterRepository.getById( porter.getPorterId()));
                    // 保存佣金明细
                    OrderCommissionLog log = new OrderCommissionLog();
                    log.setSn(order.getSn());
                    log.setOrderId(order.getId());
                    log.setProjectTitle(order.getProjectTitle());
                    log.setPorterId(porter.getPorterId());
                    log.setPorterName(porter.getPorter().getName());
                    log.setCommission(porterCommission.doubleValue());
                    log.setOrderStatus(order.getOrderStatus());
                    log.setTimeStar(porter.getTimeStar());
                    log.setTimeEnd(porter.getTimeEnd());

                    orderCommissionLogRepository.save(log);

                    // 记录护工信息
                    porterIds.add(porter.getPorterId());
                    porterNames.add(porter.getPorter().getName());
                    porterCommissions.add(porterCommission);

                } catch (Exception e) {
                    logger.error("处理护工 {} 佣金时发生异常，已跳过。异常信息：{}",
                            porter.getPorterId(), e.getMessage());
                    continue; // 跳过当前护工
                }
            }
            // 3. 准备护工ID和姓名字符串（逗号分隔）
                String porterIdsStr = porterIds.stream()
                        .map(String::valueOf)
                        .collect(Collectors.joining(","));
                String porterNamesStr = String.join(",", porterNames);
            // 保存主表记录
                OrderCommission orderCommission = new OrderCommission();
                orderCommission.setSn(order.getSn());
                orderCommission.setOrderId(order.getId());
                orderCommission.setPatientId(order.getPatientId());
                orderCommission.setProjectTitle(order.getProjectTitle());
                orderCommission.setTotal(order.getTotal());
                orderCommission.setPorterId(porterIdsStr); // 所有护工ID（逗号分隔）
                orderCommission.setPorterName(porterNamesStr); // 所有护工姓名（逗号分隔）
                orderCommission.setBedNo(order.getBedNo());
                orderCommission.setDepName(order.getDepName());
                orderCommission.setType(order.getType());
                orderCommission.setCompanyId(order.getCompanyId());
                orderCommission.setOrderStatus(order.getOrderStatus());
                orderCommission.setCommission(totalCommission.doubleValue()); // 订单总佣金
                orderCommission.setTimeStart(order.getTimeStart());
                orderCommission.setTimeEnd(order.getTimeEnd());
                orderCommission.setStartDay(order.getStartDay());
                orderCommission.setEndTime(order.getEndTime());
                orderCommission.setPatientName(order.getPatientName());

                orderCommissionRepository.save(orderCommission);

        } catch (Exception e) {
            throw new RuntimeException("处理陪护订单时发生异常：" + e.getMessage(), e);
        }
    }

    // 新增时间解析校验方法
    private LocalTime parseTime(String timeStr, String fieldName) {
        if (StringUtils.isBlank(timeStr)) {
            throw new IllegalArgumentException(fieldName + "不能为空");
        }
        try {
            return LocalTime.parse(timeStr);
        } catch (DateTimeParseException e) {
            throw new IllegalArgumentException(fieldName + "格式错误，要求格式：HH:mm:ss，实际值：" + timeStr);
        }
    }

    // 修改后的计算方法（增加防御性判断）
    private BigDecimal calculatePorterServiceHours(
            String startTimeStr,
            String endTimeStr,
            LocalTime dailyStart,
            LocalTime dailyEnd,
            boolean isCrossDay) {
        // 防御性判断
        if (StringUtils.isBlank(startTimeStr) || StringUtils.isBlank(endTimeStr)) {
            throw new IllegalArgumentException("护工服务时间不能为空");
        }

        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime start = LocalDateTime.parse(startTimeStr, formatter);
            LocalDateTime end = LocalDateTime.parse(endTimeStr, formatter);

            // 时间顺序校验
            if (start.isAfter(end)) {
                throw new IllegalArgumentException("服务开始时间不能晚于结束时间");
            }

            // 原有计算逻辑...
            // [保持原有计算逻辑不变，此处省略]
            BigDecimal totalHours = BigDecimal.ZERO;
            LocalDate currentDate = start.toLocalDate();

            while (!currentDate.isAfter(end.toLocalDate())) {
                // 构建当天的工作时间段
                LocalDateTime workStart = currentDate.atTime(dailyStart);
                LocalDateTime workEnd;
                if (isCrossDay) {
                    workEnd = currentDate.plusDays(1).atTime(dailyEnd); // 跨日：结束在次日
                } else {
                    workEnd = currentDate.atTime(dailyEnd);
                }

                // 计算当天实际服务时间段
                LocalDateTime effectiveStart = start.isAfter(workStart) ? start : workStart;
                LocalDateTime effectiveEnd = end.isBefore(workEnd) ? end : workEnd;

                if (effectiveStart.isBefore(effectiveEnd)) {
                    long minutes = Duration.between(effectiveStart, effectiveEnd).toMinutes();
                    totalHours = totalHours.add(BigDecimal.valueOf(minutes).divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP));
                }

                currentDate = currentDate.plusDays(1);
            }
            return totalHours;
        } catch (DateTimeParseException e) {
            throw new IllegalArgumentException("时间格式错误，要求格式：yyyy-MM-dd HH:mm:ss");
        }
    }






}
